<!--
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-01-22 18:44:45
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-09 18:25:43
 * @FilePath: /XMate-h5/src/components/CustomTabBar.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="tab-container">
    <div class="tabview gap-3">
      <div
        :class="['tab', active === index ? 'tab-active' : '']"
        ref="tabTag"
        v-for="(tab, index) in tabs"
        :key="index"
        @click="onClickTab(index)"
      >
        {{ tab.title }}
        <van-icon v-if="tab.iconName" :name="tab.iconName" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CustomTabBar",
  emits: ["update:active", "clickTab", "showMoreAction"],
  props: {
    tabs: {
      type: Array,
      default: () => [],
    },
    active: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {};
  },
  methods: {
    onClickTab(index) {
      this.$emit("clickTab", { tab: this.tabs[index], index: index });
      this.$emit("update:active", index);
      this.scrollToIndex(index);
    },

    scrollToIndex(index) {
      const element = this.$refs.tabTag[index];
      const container = this.$el.querySelector(".tabview");

      if (element && container) {
        // 计算元素在容器中的位置
        const elementLeft = element.offsetLeft;
        const containerWidth = container.clientWidth;
        const elementWidth = element.offsetWidth;

        // 计算滚动位置，让元素居中显示
        let scrollLeft = elementLeft - containerWidth / 2 + elementWidth / 2;

        // 边界处理
        if (index === 0) {
          scrollLeft = 0;
        } else if (index === this.tabs.length - 1) {
          scrollLeft = container.scrollWidth - containerWidth;
        }

        // 平滑滚动到指定位置
        container.scrollTo({
          left: scrollLeft,
          behavior: "smooth",
        });
      }
    },
  },

  watch: {
    active(newVal) {
      console.log("watch active", newVal);
      setTimeout(() => {
        this.scrollToIndex(newVal);
      }, 200);
    },
  },
};
</script>

<style lang="less" scoped>
.tab-container {
  padding: 0 10px;
}

.tabview {
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow-x: auto;
  height: 60px;
  padding: 0 10px;
}

.tab {
  background-color: #f4f5f6;
  padding: 4px 15px;
  color: #595959;
  border-radius: 14px;
  font-size: 14px;
  min-width: 140px;
  text-align: center;
}

.tab-active {
  color: #436dff;
  background-color: #ecf0ff;
}

::-webkit-scrollbar {
  display: none;
}
</style>
